<template>
  <div class="model-control-panel">
    <div class="panel-header">
      <h3>模型控制</h3>
      <button @click="togglePanel" class="toggle-btn">{{ isCollapsed ? '+' : '−' }}</button>
    </div>
    <div v-show="!isCollapsed" class="panel-content">
      <!-- 模型文件选择 -->
      <div class="control-group">
        <label>选择模型文件：</label>
        <div class="file-input-wrapper">
          <input 
            ref="fileInput"
            type="file" 
            accept=".gltf,.glb" 
            @change="handleFileSelection"
            :disabled="loading"
            class="file-input"
          />
          <div v-if="selectedFile" class="file-info">
            <span class="file-name">{{ selectedFile.name }}</span>
            <span class="file-size">{{ formatFileSize(selectedFile.size) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 模型位置 -->
      <div class="control-section">
        <h4>位置设置</h4>
        <div class="position-controls">
          <div class="control-row">
            <label>经度：</label>
            <input 
              v-model.number="position.longitude" 
              type="number" 
              step="0.001" 
              @input="updatePosition"
              :disabled="loading"
              class="number-input"
            />
          </div>
          <div class="control-row">
            <label>纬度：</label>
            <input 
              v-model.number="position.latitude" 
              type="number" 
              step="0.001" 
              @input="updatePosition"
              :disabled="loading"
              class="number-input"
            />
          </div>
          <div class="control-row">
            <label>高度：</label>
            <input 
              v-model.number="position.height" 
              type="number" 
              step="10" 
              @input="updatePosition"
              :disabled="loading"
              class="number-input"
            />
          </div>
        </div>
      </div>
      
      <!-- 模型姿态 -->
      <div class="control-section">
        <h4>姿态调整</h4>
        <div class="orientation-controls">
          <div class="control-row">
            <label>方位角：</label>
            <input 
              v-model.number="orientation.heading" 
              type="range" 
              min="0" 
              max="360" 
              @input="updateOrientation"
              :disabled="loading"
              class="range-input"
            />
            <span class="value-display">{{ orientation.heading }}°</span>
          </div>
          <div class="control-row">
            <label>俯仰角：</label>
            <input 
              v-model.number="orientation.pitch" 
              type="range" 
              min="-90" 
              max="90" 
              @input="updateOrientation"
              :disabled="loading"
              class="range-input"
            />
            <span class="value-display">{{ orientation.pitch }}°</span>
          </div>
          <div class="control-row">
            <label>翻滚角：</label>
            <input 
              v-model.number="orientation.roll" 
              type="range" 
              min="-180" 
              max="180" 
              @input="updateOrientation"
              :disabled="loading"
              class="range-input"
            />
            <span class="value-display">{{ orientation.roll }}°</span>
          </div>
        </div>
      </div>
      
      <!-- 模型缩放 -->
      <div class="control-section">
        <h4>缩放设置</h4>
        <div class="control-row">
          <label>缩放比例：</label>
          <input 
            v-model.number="scale" 
            type="range" 
            min="0.1" 
            max="10" 
            step="0.1" 
            @input="updateScale"
            :disabled="loading"
            class="range-input"
          />
          <span class="value-display">{{ scale.toFixed(1) }}x</span>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="control-section">
        <div class="action-buttons">
          <button @click="loadModel" class="action-btn primary" :disabled="!selectedFile || loading">
            <span v-if="loading">加载中...</span>
            <span v-else>加载模型</span>
          </button>
          <button @click="loadTestCube" class="action-btn secondary" :disabled="loading">
            测试立方体
          </button>
          <button @click="removeModel" class="action-btn secondary" :disabled="loading || !hasModel">
            移除模型
          </button>
          <button @click="centerOnModel" class="action-btn secondary" :disabled="loading || !hasModel">
            聚焦模型
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { ModelPosition, ModelOrientation } from '../types/model'

interface Props {
  loading?: boolean
  hasModel?: boolean
}

withDefaults(defineProps<Props>(), {
  loading: false,
  hasModel: false
})

const emit = defineEmits<{
  loadModel: [file: File, position: ModelPosition]
  removeModel: []
  centerOnModel: []
  updatePosition: [position: ModelPosition]
  updateOrientation: [orientation: ModelOrientation]
  updateScale: [scale: number]
  loadTestCube: []
}>()

// 响应式数据
const isCollapsed = ref(false)
const selectedFile = ref<File | null>(null)
const fileInput = ref<HTMLInputElement>()

const position = reactive<ModelPosition>({
  longitude: 116.397,
  latitude: 39.909,
  height: 0
})

const orientation = reactive<ModelOrientation>({
  heading: 0,
  pitch: 0,
  roll: 0
})

const scale = ref(1.0)

// 方法
const togglePanel = () => {
  isCollapsed.value = !isCollapsed.value
}

const handleFileSelection = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 验证文件类型
  const allowedTypes = ['.gltf', '.glb']
  const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'))
  
  if (!allowedTypes.includes(fileExtension)) {
    alert('请选择 .gltf 或 .glb 格式的模型文件')
    target.value = ''
    return
  }

  // 验证文件大小（限制100MB）
  const maxSize = 100 * 1024 * 1024 // 100MB
  if (file.size > maxSize) {
    alert('文件太大，请选择小于100MB的文件')
    target.value = ''
    return
  }

  selectedFile.value = file
  console.log('已选择文件:', file.name, '大小:', formatFileSize(file.size))
}

const loadModel = () => {
  if (!selectedFile.value) {
    alert('请先选择一个模型文件')
    return
  }
  
  emit('loadModel', selectedFile.value, { ...position })
}

const loadTestCube = () => {
  emit('loadTestCube')
}

const removeModel = () => {
  emit('removeModel')
  resetControls()
}

const centerOnModel = () => {
  emit('centerOnModel')
}

const updatePosition = () => {
  emit('updatePosition', { ...position })
}

const updateOrientation = () => {
  emit('updateOrientation', { ...orientation })
}

const updateScale = () => {
  emit('updateScale', scale.value)
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 重置控制面板
const resetControls = () => {
  position.longitude = 116.397
  position.latitude = 39.909
  position.height = 0
  orientation.heading = 0
  orientation.pitch = 0
  orientation.roll = 0
  scale.value = 1.0
  selectedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 暴露方法给父组件
defineExpose({
  resetControls,
  setPosition: (pos: ModelPosition) => {
    Object.assign(position, pos)
  },
  setOrientation: (ori: ModelOrientation) => {
    Object.assign(orientation, ori)
  },
  setScale: (s: number) => {
    scale.value = s
  }
})
</script>
